from flask import Flask, request, jsonify, stream_with_context
import JumpRope as jr
import os
import time
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import webbrowser

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'videos'
app.config['static_folder'] = 'static'
socketio = SocketIO(app, cors_allowed_origins='*')
CORS(app)

tasks = {}

if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])

@app.route('/api/uploadVideo', methods=['POST'])
def upload_video():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'})
    if file:
        # 根据时间戳重命名文件
        file.filename = str(int(time.time())) + '_' + file.filename
        # 下载文件
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
        return jsonify({'message': 'success', 'file_path': os.path.join(app.config['UPLOAD_FOLDER'], file.filename)})

# 请求开始摄像头 并返回任务名称
@app.route('/api/starCamera', methods=['GET'])
def start_camera():
    # 根据时间戳生成随机名称
    task_name = str(int(time.time()))
    detector = jr.JumpRopeDetector()

    tasks[task_name] = detector

    return jsonify({'message': 'success', 'task_name': task_name})


name_space = '/calPic'

@socketio.on('connect', namespace=name_space)
def handle_connect():
    print('Client connected')

@socketio.on('disconnect', namespace=name_space)
def handle_disconnect():
    for taskName in tasks:
        detector = tasks[taskName]
        detector.stopTask()
    print('客户端断开连接')

@socketio.on('stop', namespace=name_space)
def handle_stop(data):

    taskName = data
    print(taskName)
    print('stop', taskName)
    if taskName not in tasks:
        emit('error', {'message': 'No task found'})
        return
    detector = tasks[taskName]
    detector.stopTask()
    del tasks[taskName]
    print(tasks)
    #断开连接

# 开始计数
@socketio.on('startCount', namespace=name_space)
def handle_start_count(data):
    taskName = data
    if taskName not in tasks:
        emit('error', {'message': 'No task found'})
        return
    detector = tasks[taskName]
    detector.startCount()

# 停止计数
@socketio.on('endCount', namespace=name_space)
def handle_stop_count(data):
    taskName = data
    if taskName not in tasks:
        emit('error', {'message': 'No task found'})
        return
    detector = tasks[taskName]
    detector.stopCount()

# 打开摄像头
@socketio.on('startCamera', namespace=name_space)
def handle_start_camera(data):
    task_name = data
    if task_name not in tasks:
        emit('error', {'message': 'No task found'})
        return
    detector = tasks[task_name]
    detector.detectCamera()
    

 

# 预测视频
@socketio.on('calPic', namespace=name_space)
def handle_process_video(data):
    file_path = data   
    if not file_path:
        emit('error', {'message': 'No file path provided'})
        return     

    detector = jr.JumpRopeDetector()
    task_name = str(int(time.time()))
    emit('taskName', {'taskName': task_name})
    tasks[task_name] = detector
    detector.detectVideo(file_path) 

@app.route('/', methods=['GET'])
def index():
    # 返回主页 static/index.html
    return app.send_static_file('index.html')

@app.route('/assets/<path:filename>', methods=['GET'])
def assets(filename):

    return app.send_static_file(f'assets/{filename}')





if __name__ == '__main__':

    app.run(port='7921', host='0.0.0.0', threaded=True, debug=True)
    # 打开浏览器
    webbrowser.open('http://127.0.0.1:7921/')